

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Message
import android.widget.ImageView
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

object HttpUtil{
    //午餐函数
    fun sendOKHttpRequest(url:String, callback: okhttp3.Callback){
        val client=OkHttpClient()
        val request=Request.Builder()
            .url(url)
            .build()
        client.newCall(request).enqueue(callback)
    }
    //有参函数
    fun sendOKHttpRequest(
        url:String,
        data:Map<String,String>,
        callback: okhttp3.Callback
    ){
        val client=OkHttpClient()
        val requestBody=FormBody.Builder()
        for(key in data.keys) {
            requestBody.add(key,data.get(key).toString())
        }
        println( requestBody.build().toString());

        val request=Request.Builder()
            .url(url)
            .post(requestBody.build())
            .build()
        println(request.toString());

        client.newCall(request).enqueue(callback)

    }
    //获得图片
//    fun getImage()
     fun getImage(url: String?,imageView:ImageView): Bitmap? {
        var image: Bitmap? =null
        var handle=object :Handler(){
            override fun handleMessage(msg: Message) {
                when(msg.what){
                    1->{
                        image=msg.obj as Bitmap

                        imageView.setImageBitmap(image)

                    }
                }
            }
        }
        val thread = thread {
            val urlConnection = URL(url)
            val connection = urlConnection.openConnection() as HttpURLConnection
            connection.connectTimeout = 5000
            val msg = Message()
            if (connection.responseCode == HttpURLConnection.HTTP_OK) {
                var inputStream = connection.inputStream
                val image = BitmapFactory.decodeStream(inputStream)
                msg.obj = image
                msg.what = 1
                handle.sendMessage(msg)
            }
        }
        return image
    }
    fun getImageBitmap(url: String?):Bitmap?{
        val urlConnection=URL(url)
        val connection=urlConnection.openConnection() as HttpURLConnection
        connection.connectTimeout=5000
        val msg= Message()
        var image: Bitmap? =null
        if(connection.responseCode==HttpURLConnection.HTTP_OK){
            var inputStream=connection.inputStream
            image =BitmapFactory.decodeStream(inputStream)

        }
        return image
    }

}

